from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
import threading

# 帮我们直接运行此文件时，可以加载到上级目录的ui包
sys.path.append("../")

from ui.Ui_serial_assist_widget import Ui_SerialAssistWidget
from drivers.driver_serial import *
from views.serial_setting_dialog import *
from common import utils
from drivers import *


class SerialAssistWidget(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_SerialAssistWidget()
        self.ui.setupUi(self)

        self.devices = None
        self.sd: SerialDevice = None

        self.init_ui()
        self.refresh_devices()

    def refresh_devices(self):
        """
        扫描串口设备
        """
        print("扫描设备")  # 提示
        self.devices = scan_serial_ports()
        print(self.devices)
        devices_names = [item[0] for item in self.devices]
        self.ui.cb_device.clear()
        self.ui.cb_device.addItems(devices_names)

    def show_setting_dialog(self):
        """
        显示串口设置窗口
        """
        print("测试点击btn_setting是否生效")
        dialog = SerialSettingDialog()
        rst = dialog.exec_()
        print(rst)
        if rst == QDialog.Accepted:
            print("accept")
            print("baudrate:", dialog.baudrate)
            print("baudrate:", dialog.data_bits)
            self.ui.cb_baudrate.setCurrentIndex(
                self.ui.cb_baudrate.findText(dialog.baudrate)
            )
            
    def update_serial_ui(self):
        """
        串口连接和关闭成功后,更新UI
        """
        if self.sd is not None:
            self.ui.btn_connect.setText(
                "断开连接(已连接)"
            )  # 更改btn_connect连接按钮的文字内容
            self.ui.label_connect.setPixmap(QPixmap(":/icon/connect"))
        else:
            self.ui.btn_connect.setText("连接设备")  # 更改btn_connect连接按钮的文字内容
            self.ui.label_connect.setPixmap(QPixmap(":/icon/disconnect"))

    def run_serial_assist(self, current_port, baud_rate):
        self.sd = SerialDevice(
            current_port, baud_rate, timeout=None
        )  # 替换为您的串口名称、波特率和超时时间
        success, message = self.sd.open()
        print("Open serial port:", message)

        if not self.sd.open():
            print("串口连接失败")
            self.sd = None
            self.update_serial_ui()
            return

        print("串口连接成功")
        self.update_serial_ui()  # 串口连接成功更新Ui

        try:
            self.sd.write("串口\n".encode("UTF-8"))  # 发送数据
            # print(sd.readline())  # 读取10个字节的数据
            while True:
                data = self.sd.readline()   #读取数据
                # data = sd.read_bytes()
                if data:
                    msg = utils.decode_data(data)
                    print(msg)
                    self.ui.edit_recieve_text.append(msg) 
                else:
                    break
        except Exception as e:
            print("Error:", str(e))
        finally:
            self.sd.close()
            self.sd = None
            self.update_serial_ui()  # 串口断开成功更新Ui

    def on_connect_clicked(self):
        if self.sd is not None:
            self.sd.close()
            self.sd = None
            self.update_serial_ui()  # 串口断开成功更新Ui
            return   
                     
        device = self.devices[
            self.ui.cb_device.currentIndex()
        ]  # 取出当前cb_device中的内容
        print("连接串口设备：", device)
        current_port = device[0]  # 取出当前的端口号
        baud_rate = int(
            self.ui.cb_baudrate.currentText()
        )  # 将cb_baudrate中的文本提取出来

        thread = threading.Thread(
            target=self.run_serial_assist, args=(current_port, baud_rate), daemon=True
        )   # 创建串口数据处理的保护线程
        thread.start()
        
    def on_send_clicked(self):
        if not self.sd.open():
            print("请先连接设备")
            QMessageBox.warning(self, "警告", "请先连接设备")
            return
        send_text = self.ui.edit_send_text.toPlainText() # 获取发送区的数据
        # 判断输入数据是否为空
        if send_text == "":
            print("请先输入要发送的数据")
            QMessageBox.warning(self, "警告", "请先输入要发送的数据")
            return
        self.sd.write(f"{send_text}\n".encode("UTF-8")) # 将获取的数据发送出去

    def init_ui(self):
        self.ui.btn_refresh.clicked.connect(self.refresh_devices)
        self.ui.btn_setting.clicked.connect(self.show_setting_dialog)
        self.ui.btn_connect.clicked.connect(self.on_connect_clicked)
        self.ui.btn_send.clicked.connect(self.on_send_clicked)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = SerialAssistWidget()
    window.show()

    sys.exit(app.exec_())
